package com.zsr.example.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zsr.example.util.constants.SysLogConstants;
import org.springframework.web.util.ContentCachingRequestWrapper;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

/**
 * 解析请求工具类
 * @author zhousiren
 * @date 2021/12/18 23:38
 */
public class RequestUtil {
    /**
     * 读取请求信息,转换为json
     */
    public static JSONObject getRequestInfo(HttpServletRequest req) {
        JSONObject requestInfo = new JSONObject();
        try {
            StringBuffer requestURL = req.getRequestURL();
            requestInfo.put(SysLogConstants.REQUEST_URL, requestURL);
            String method = req.getMethod();
            requestInfo.put(SysLogConstants.METHOD, method);//get/post/put
            if (req.getQueryString() != null) {
                requestInfo.put(SysLogConstants.QUERY_STRING, URLDecoder.decode(req.getQueryString(), "UTF-8"));//get请求key=value的形式参数
            }
            //String remoteAddr = req.getRemoteAddr(); //获取用户真实IP地址，不使用request.getRemoteAddr();的原因是有可能用户使用了代理软件方式避免真实IP地址。
            requestInfo.put(SysLogConstants.REMOTE_ADDR, IPUtil.getIpAddress(req));
            if (req instanceof ContentCachingRequestWrapper) {
                ContentCachingRequestWrapper wrapper = (ContentCachingRequestWrapper) req;
                String bodyStr = new String(wrapper.getContentAsByteArray(), StandardCharsets.UTF_8);
                if (bodyStr.startsWith("{")) {
                    JSONObject jsonObject = JSON.parseObject(bodyStr);
                    requestInfo.put(SysLogConstants.REQUEST_BODY, jsonObject);
                }
            }
            //
        } catch (Exception e) {
            requestInfo.put(SysLogConstants.PARSE_ERROR, e.getMessage());
        }
        return requestInfo;
    }
}
